<?php
namespace app\job;

use app\api\controller\v1\Clue as ClueModel;
use think\Db;
use think\Exception;
use think\Queue;
use think\queue\Job;

//php think queue:listen --queue ClueLossPrice
//第四步线索池累加成本
class ClueLossPrice{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data){
        // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                $job->delete();
                // 也可以重新发布这个任务
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }


    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }

    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function doHelloJob($data) {
        try {
            $dateTime=date('Y-m-d',$data['time'][1][0]);
            $map['a.time']=$dateTime;
            $map['a.clue_num']=['=',0];

            $map3['a.create_time'] = $data['time'];

            model('ClueCostLog')->alias('a')->where($map)->update(['is_cost'=>0]);

            $list=model('ClueCostLog')->alias('a')
                ->where($map)->chunk(20,function($users) use ($map3) {
                    $log=[];
                    $updateId=[];
                    foreach ($users as $loginfo) {
                        if($loginfo['money']>0){
                            $clue=model('clue')->alias('a')->field('a.id,a.xz_price price,xz_price2,a.xz_true_price true_price,xz_true_price2,create_time')
                                ->where(['a.pro_id' => $loginfo['pro_id'], 'a.city' => $loginfo['city']])->where($map3)->select();

                            if(!empty($clue)){
                                $allprice=array_sum(array_column($clue,'price'));

                                $alltrue_price=array_sum(array_column($clue,'true_price'));

                                $allxz_price2=array_sum(array_column($clue,'xz_price2'));
                                $all_true_price2=array_sum(array_column($clue,'xz_true_price2'));

                                $clueNum=count($clue);

                                //金额占比
                                foreach ($clue as $val){
                                    $inserDataLog['clue_id']=$val['id'];
                                    $inserDataLog['from_cost_id']=$loginfo['id'];
                                    $inserDataLog['create_time']=time();
                                    $inserDataLog['clue_time']=strtotime($val['create_time']);
                                    $inserDataLog['xz_type']=1;
                                    if($val['price']>0){
                                        $rate1=bcdiv($val['price'],$allprice,4);
                                        $price=round(bcmul($loginfo['money'],$rate1,4),2);
                                    }else{
                                        if($allprice==0){
                                            $price=round(bcdiv($loginfo['money'],$clueNum,4),2);
                                        }else{
                                            $price=0;
                                        }
                                    }
                                    $inserDataLog['price']=$price;
                                    if($val['true_price']>0){
                                        $rate2=bcdiv($val['true_price'],$alltrue_price,4);
                                        $true_price=round(bcmul($loginfo['true_consume'],$rate2,4),2);
                                    }else{
                                        if($alltrue_price==0){
                                            $true_price=round(bcdiv($loginfo['true_consume'],$clueNum,4),2);
                                        }else{
                                            $true_price=0;
                                        }
                                    }
                                    $inserDataLog['true_price']=$true_price;

                                    if($price>0||$true_price>0){
                                        $log[]=$inserDataLog;
                                    }
                                    //修改LOG2
                                    $inserDataLog['xz_type']=2;
                                    if($val['xz_price2']>0){
                                        $rate1=bcdiv($val['xz_price2'],$allxz_price2,4);
                                        $price2=round(bcmul($loginfo['money'],$rate1,4),2);
                                    }else{
                                        if($allxz_price2==0){
                                            $price2=round(bcdiv($loginfo['money'],$clueNum,4),2);
                                        }else{
                                            $price2=0;
                                        }
                                    }
                                    $inserDataLog['price']=$price2;
                                    if($val['xz_true_price2']>0){
                                        $rate2=bcdiv($val['xz_true_price2'],$all_true_price2,4);
                                        $true_price2=round(bcmul($loginfo['true_consume'],$rate2,4),2);
                                    }else{

                                        if($all_true_price2==0){
                                            $true_price2=round(bcdiv($loginfo['true_consume'],$clueNum,4),2);
                                        }else{
                                            $true_price2=0;
                                        }
                                    }
                                    $inserDataLog['true_price']=$true_price2;
                                    if($price2>0||$true_price2>0){
                                        $log[]=$inserDataLog;
                                    }


                                    if($price>0||$true_price>0||$price2>0||$true_price2>0){
                                        Db::name('clue')->where('id',$val['id'])->inc('xz_price',$price)->inc('xz_true_price',$true_price)->inc('xz_price2',$price2)->inc('xz_true_price2',$true_price2)->update();
                                    }

                                }
                                $updateId[]=$loginfo['id'];
//                                model('ClueCostLog')->where('id',$loginfo['id'])->update(['is_cost'=>1]);
                            }
                        }
                    }
                    if(!empty($log)){
                        Db::name('clue_zero_cost_details')->insertAll($log);
                    }
                    if(!empty($updateId)){
                        model('ClueCostLog')->whereIn('id',$updateId)->update(['is_cost'=>1]);
                    }
                });
            echo json_encode($data,JSON_UNESCAPED_UNICODE);
            $jobHandlerClassName  = 'app\job\ClueAllLossPrice@fire';
            // 2.当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName     = "ClueAllLossPrice";

            $jobData = ['time'=>$data['time']];//时间戳

            $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
            return true;
        }catch (Exception $e){
            $errData=[
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage(),
                'flie'=>$e->getFile(),
                'line'=>$e->getLine(),
            ];
            trace($errData,'error');
            return true;
        }
    }

}